<template>
  <div class="search-suggestion">
    <van-cell
      v-for="(suggestion, index) in suggestions"
      :key="index"
      icon="search"
      @click="$emit('search',suggestion)"
      ><div slot="title" v-html="highlight(suggestion)"></div
    ></van-cell>
  </div>
</template>

<script>
import { debounce } from "lodash";
import { getSearchSuggestionList } from "@/api/search";
export default {
  name: "searchSuggestion",
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      suggestions: [], // 联想建议列表
    };
  },
  watch: {
    searchText: {
      immediate: true,
      handler: debounce(async function (newVal) {
        let { data } = await getSearchSuggestionList(newVal);
        this.suggestions = data.data.options;
        if (!data.data.options[0]) this.suggestions = [];
      }, 200),
    },
  },
  methods: {
    // 搜索关键词在联想建议列表中高亮展示
    highlight(suggestion) {
      return suggestion.replace(
        new RegExp(this.searchText, "gi"),
        "<span style='color:red'>$&</span>"
      );
    },
  },
};
</script>

<style></style>
